import {
  ds
} from '../../../tools/data'
import {
  users
} from '../../../tools/users'
import {
  localData
} from '../../../tools/localData'
import {
  checkTool
} from '../../../tools/check'
import {
  ui
} from '../../../tools/ui'
import {
  pages
} from '../../../tools/pages'
import {
  dsFiles
} from '../../../tools/dsFiles'

const cloudPrefix = getApp().globalData.cloudPrefix

Page({
  data: {
    item: {},
    msgs: [],
    userInfo: {}, // user
  },
  onLoad(options) {
    this.setData({
      action: options.action || 'new'
    })
    this.options = options
  },
  async onBackTap() {
    if (!await ui.confirmx('确定返回吗？')) return
    wx.navigateBack()
  },
  onSelMsgType() {
    ui.actionSheet({
      text: '文本',
      image: '图片',
      goods: '商品',
      ticket: '水票'
    }, (desc, key) => {
      const item = this.data.item
      this.setData({
        item: {
          ...item,
          msgType: key,
          msgTypeDesc: desc
        }
      })
      if (key == 'text') {
        ui.text('设置消息文本', '输入文本', (confirm, text) => {
          if (confirm) {
            this.addItemData('text', text)
          }
        })
      } else if (key == 'image') {
        wx.navigateTo({
          url: '/pages/common/imgSelect/index',
        })
      } else if (key == 'goods') {
        wx.navigateTo({
          url: '/pages/common/goodsManage/index',
        })
      } else if (key == 'ticket') {
        wx.navigateTo({
          url: '/pages/common/goodsManage/index?ticket=true',
        })
      }
    })
  },
  imgSelected(files, tag) {
    if (files?.length > 0) {
      const src = files[0]
      this.addItemData('src', src)
      this.addItemData('srcDesc', src.substr(src.lastIndexOf('/') + 1))
    }
  },
  goodsSelected(goods, options) {
    if (!goods?.id) return
    this.addItemData('id', goods.id)
    this.addItemData('title', goods.title)
  },
  addItemData(name, value) {
    const item = this.data.item
    item[name] = value
    this.setData({
      item
    })
  },
  submitTap() {
    const {
      msgs,
      title,
    } = this.data
    checkTool.check([{
      value: title,
      title: '标题'
    }, {
      value: msgs,
      title: '消息列表',
      fn: ele => ele.length > 0
    }])
    pages.back(prePage => {
      prePage.fastReplyCallback && prePage.fastReplyCallback({
        title,
        contents: msgs
      }, this.options)
    })
  },
  onClickCell({
    currentTarget
  }) {
    const {
      dataset
    } = currentTarget;

    switch (dataset.type) {
      case 'gender':
        ui.actionSheet(['男', '女', '保密'], res => {
          let userInfo = dataset.userinfo
          userInfo.personInfo = userInfo.personInfo || {}
          userInfo.personInfo.gender = res
          this.updateUserInfo(userInfo)
        })
        break;
      default: {
        break;
      }
    }
  },
  onValueChange(e) {
    const {
      type
    } = e.currentTarget.dataset
    const {
      value
    } = e.detail

    this.setData({
      title: value
    })
  },
  getPhoneNumber(event) {
    const userInfo = event.currentTarget.dataset.userinfo
    users.getMobile(event, phoneNumber => {
      userInfo.phoneNumber = phoneNumber
      this.updateUserInfo(userInfo)
    })
  },
  onClose() {
    this.setData({
      typeVisible: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e.detail;
    this.setData({
        typeVisible: false,
        'personInfo.gender': value,
      },
      () => {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '设置成功',
          theme: 'success',
        });
      },
    );
  },
  async toModifyAvatar() {
    try {
      const tempFilePath = await new Promise((resolve, reject) => {
        wx.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            const {
              path,
              size
            } = res.tempFiles[0];
            if (size <= 10485760) {
              resolve(path);
            } else {
              reject({
                errMsg: '图片大小超出限制，请重新上传'
              });
            }
          },
          fail: (err) => reject(err),
        });
      });
      const tempUrlArr = tempFilePath.split('/');
      const tempFileName = tempUrlArr[tempUrlArr.length - 1];
      Toast({
        context: this,
        selector: '#t-toast',
        message: `已选择图片-${tempFileName}`,
        theme: 'success',
      });
    } catch (error) {
      if (error.errMsg === 'chooseImage:fail cancel') return;
      Toast({
        context: this,
        selector: '#t-toast',
        message: error.errMsg || error.msg || '修改头像出错了',
        theme: 'fail',
      });
    }
  },
  deliFeeClick() {
    const {
      userInfo
    } = this.data
    const nickName = userInfo.personInfo?.nickName || ''
    wx.navigateTo({
      url: `/pages/usercenter/staff/deliveryFee/deliFee?staffId=${userInfo._id}&nickName=${nickName}`,
    })
  },
  deductFeeClick() {
    const {
      userInfo
    } = this.data
    const nickName = userInfo.personInfo?.nickName || ''
    wx.navigateTo({
      url: `/pages/usercenter/staff/deductFee/deductFee?staffId=${userInfo._id}&nickName=${nickName}`,
    })
  },
  onAddReplyTap() {
    checkTool.check(this.makeCheckFields())
    const msgs = this.data.msgs
    msgs.push(this.data.item)
    this.setData({
      msgs
    })
  },
  makeCheckFields() {
    const {
      title,
      item
    } = this.data
    return [{
      value: item.msgType,
      title: '类型'
    }, {
      value: (() => {
        const msgType = item.msgType
        if (msgType == 'text') return item.text
        if (msgType == 'image') return item.src
        if (msgType == 'goods') return item.id
        if (msgType == 'ticket') return item.id
      })(),
      title: '消息内容'
    }]
  },
  onUpDownItemTap(e) {
    const index = ui.eventData(e, 'index'),
      upDown = ui.eventData(e, "updown")
    const {
      msgs
    } = this.data

    if (index == 0 && upDown == 'up') return
    if (index == msgs.length - 1 && upDown == 'down') return
    this.setData({
      msgs: this.switchArray(msgs, index, upDown == 'up' ? (index - 1) : (index + 1))
    })
  },
  switchArray(arr, i, j) {
    const tmp = arr[i]
    arr[i] = arr[j]
    arr[j] = tmp
    return arr
  },
  onDeleteReplyTap(e) {
    const index = ui.eventData(e, 'index')
    const msgs = this.data.msgs
    msgs.splice(index, 1)
    this.setData({
      msgs
    })
  },
  onEditReplyTap(e) {
    const item = ui.eventData(e, 'item')
    this.setData({
      item
    })
  }

});